package cn.zy.amyan.core.codec;

import cn.zy.amyan.core.base.DataBase;
import cn.zy.amyan.core.util.AySerializer;
import cn.zy.amyan.core.util.KryoSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

/**
 * 解码类
 * @author 子言
 * @date 2024/5/5 下午 15:14
 */
public class AyDecode<T extends DataBase> extends ReplayingDecoder<Void> {
	AySerializer serializerUtil = new KryoSerializer();

	private Class<T> clazz;

	public AyDecode(Class<T> clazz) {
		this.clazz = clazz;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		// 读取消息长度并创建字节数组
		byte[] bytes = new byte[in.readInt()];
		// 读取消息
		in.readBytes(bytes);
		// 反序列化数据
		DataBase dataBase = serializerUtil.deserializer(bytes, clazz);
		out.add(dataBase);
	}
}
